package org.example.myframework.frame.demo.domain.base;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @name: 分页构造类
 * @author: xyy
 * @create: 2021/6/7 20:25
 * @description: 基于mybatis-plus的分页相关构造工具
 */
public class PageGenerator {

    /**
     * 统一分页器 请求转mybaits plus分页
     * @param ro
     * @param <E>
     * @return
     */
    public static <E> Page<E> getPage(PageRo<E> ro) {
        Page<E> page = new Page<>();
        //需要先进行驼峰转化
        if (ro.getAscs() != null && ro.getAscs().length > 0) {
            List<OrderItem> collect = Arrays.stream(ro.getAscs())
                    .map(f->OrderItem.asc(CamelCaseUtil.toUnderlineCase(f))).collect(Collectors.toList());
            page.addOrder(collect);
        }
        if (ro.getDescs() != null && ro.getDescs().length > 0) {
            List<OrderItem> collect = Arrays.stream(ro.getDescs())
                    .map(f->OrderItem.desc(CamelCaseUtil.toUnderlineCase(f))).collect(Collectors.toList());
            page.addOrder(collect);
        }
        page.setSize(ro.getPageSize());
        page.setCurrent(ro.getPageIndex());
        return page;
    }

    /**
     * 统一分页器 mybaits plus分页转返回
     * @param iPage
     * @return
     */
    public static <E> PageVo<E>  toPage(IPage<E>  iPage) {
        return new PageVo(
                iPage.getTotal(),iPage.getPages(),iPage.getCurrent(),iPage.getSize(),iPage.getRecords()
        );
    }


}
